package u1project.server;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

//专门处理用户的操作
//登录验证
//注册
//注册验证
public class UserManager {
	//
	public static final String FILE = "users.xml";

	public boolean login(String u, String p) {
		SAXReader reader = new SAXReader();
		try {
			Document doc = reader.read(new File(FILE));
			Element e = (Element) doc.selectSingleNode("/users/user[name=\"" + u + "\"][pass=\"" + p + "\"]");
			return e != null;
		} catch (DocumentException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

		return false;
	}

	// 检查两次密码是否一致，还要判断name是否重复
	public boolean reg(String name, String pass, String repeatpass) {
		if (!pass.equals(repeatpass)) {
			return false;
		}
		SAXReader reader = new SAXReader();
		try {
			Document doc = reader.read(new File(FILE));
			Element e = (Element) doc.selectSingleNode("/users/user[name=\"" + name + "\"]");
			if (e != null) {
				return false;
			}
			Element root = doc.getRootElement();
			Element e2 = root.addElement("user");
			e2.addElement("name").setText(name);
			e2.addElement("pass").setText(pass);
			OutputFormat out = OutputFormat.createPrettyPrint();
			out.setEncoding("utf-8");

			XMLWriter xw = new XMLWriter(new FileWriter(FILE), out);
			xw.write(doc);
			xw.close();
			return true;

		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return false;
	}

	public static void main(String[] args) {
		UserManager u = new UserManager();
//		boolean f = u.login("xiaoli", "yahui");
		boolean f = u.reg("wanglaotai", "123", "123");
		System.out.println(f);
	}
}
